import { InjectRepository } from "@nestjs/typeorm";
import { Between, Repository } from "typeorm";
import { OrderEntity } from "./entities/order.entity";
import { isNil } from "ramda";
import { getPagination, throwHttp } from "src/utlis";
import { CreateOrderDto, GetOrderDto, UpdateOrderDto } from "./dto/order.dto";
import { OrderState } from "src/dictionaries/index.enum";
import { isTrue } from "src/utlis/tools";
import { UseFilters } from "@nestjs/common";
import { HttpExceptionFilter } from "src/common/http-exception.filter";
import { UserService } from "../user/user.service";
import { TokenDto } from "src/common/auth/constants";

export class OrderService {
    constructor(
        @InjectRepository(OrderEntity)
        private readonly OrderRepository: Repository<OrderEntity>,
        private readonly userService: UserService,
    ) { }
    generateOrderNumber(): string {
        const date = new Date();
        // Formatting the date as yyyyMMddHHmmss
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        const formattedDate = `${year}${month.toString().padStart(2, '0')}${day.toString().padStart(2, '0')}${hours.toString().padStart(2, '0')}${minutes.toString().padStart(2, '0')}${seconds.toString().padStart(2, '0')}`;

        // Generating a random number between 100000000 and 999999999
        const randomNumber = Math.floor(Math.random() * 900000000) + 100000000;

        // Combining all parts to form the order number
        return `SS${formattedDate}${randomNumber}`;
    }
    /** 获取订单 */
    async getOrderPage(params: GetOrderDto) {
        try {
            const {
                orderNo,
                status,
                userId,
                createTimeStart,
                createTimeEnd,
                payType,
                type,
            } = params;
            const where: GetOrderDto = {
                orderNo,
                status,
                userId,
                payType,
                type
            };
            // 创建时间筛选
            if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
                where.createDate = Between(createTimeStart, createTimeEnd);
            }
            const { pageSize, pageNum } = getPagination({
                pageSize: params.pageSize,
                pageNum: params.pageNum,
            });
            const [data, total] = await this.OrderRepository.findAndCount({
                where,
                cache: true,
                order: { createDate: 'DESC' },
                skip: pageNum * pageSize,
                take: pageSize,
            });
            return {
                data,
                total,
                pageSize,
                pageNum: pageNum + 1,
            };
        } catch (error) {
            throwHttp(error.message);
        }
    }
    /** 创建订单 */
    @UseFilters(new HttpExceptionFilter())
    async createOrder(body: CreateOrderDto, operatorBy: TokenDto) {
        try {
            // const { userId, amount, payType, type } = body;
            // const order = new OrderEntity();
            // order.userId = userId;
            // order.amount = amount;
            // order.payType = payType;
            // order.type = type;
            // order.status = OrderState.COMPLETED;
            // const user = await this.userService.getUserInfo({
            //     id: userId
            // })
            // if (!isTrue(user)) {
            //     throwHttp('用户不存在');
            //     return
            // }
            // const result = await this.OrderRepository.manager.save(order);
            // if (isTrue(result)) {
            //     return '订单创建成功';
            // }
            // return '订单创建失败';
        } catch (error) {
            throwHttp(error.message);
        }
    }
    /** 更新订单 */
    @UseFilters(new HttpExceptionFilter())
    async updateOrder(body: UpdateOrderDto, operatorBy: TokenDto) {
        try {
            const { userId, status, payType, id, type } = body;
            const order = await this.getOrderInfo({
                id,
            });
            if (!isTrue(order)) {
                throwHttp('订单不存在');
                return;
            }
            const { affected } = await this.OrderRepository
                .createQueryBuilder()
                .update(OrderEntity)
                .set({
                    userId,
                    status,
                    payType,
                    type
                })
                .where('id = :id', { id })
                .execute();

            if (affected) {
                return '更新成功';
            }
            throwHttp('更新失败');
        } catch (error) {
            throwHttp(error.message);
        }
    }
    /** 获取订单详情 */
    @UseFilters(new HttpExceptionFilter())
    async getOrderInfo(where) {
        try {
            return await this.OrderRepository.findOne({
                where,
                cache: true,
            });
        } catch (error) {
            throwHttp(error.message);
        }
    }
}
